﻿using System;
using System.Configuration;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace FBS.Framework
{
    public class Deserializer
    {

        /// <summary>
        /// Converts the String to UTF8 Byte array and is used in De serialization
        /// </summary>
        /// <param name="pXmlString"></param>
        /// <returns></returns>
        private static Byte[] StringToUTF8ByteArray(string pXmlString)
        {
            UTF8Encoding encoding = new UTF8Encoding();

            byte[] byteArray = encoding.GetBytes(pXmlString);
            return byteArray;
        }

        private static Byte[] StringToISO_8859_1ByteArray(string pXmlString)
        {

            System.Text.Encoding iso_8859_1 = System.Text.Encoding.GetEncoding("iso-8859-1");
            System.Text.Encoding utf_8 = System.Text.Encoding.UTF8;

            // Unicode string. 
            string s_unicode = pXmlString;

            // Convert to ISO-8859-1 bytes. 
            byte[] isoBytes = iso_8859_1.GetBytes(s_unicode);

            // Convert to UTF-8.
            byte[] bytes = System.Text.Encoding.Convert(iso_8859_1, utf_8, isoBytes);

            //byte[] bytes = Encoding.GetEncoding("UTF-8").GetBytes(pXmlString);

            return bytes;

        }

        static void SaveMemoryStream2XML(MemoryStream mstr)
        {
            //Salvando o MemoryStrem em um arquivo físico
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;

            using (FileStream fs = File.Open(ConfigurationManager.AppSettings["RepositorioXML"].ToString() + Guid.NewGuid().ToString().Split('-')[0] + "_" + DateTime.Now.ToString("ddMMyyyy_hhmmss") + ".XML", FileMode.Create, FileAccess.Write))
            {
                mstr.WriteTo(fs);
            }
        }

        /// <summary>
        /// Reconstruct an object from an XML string
        /// </summary>
        /// <param name="xml"></param>
        /// <returns></returns>
        public static T DeserializeObject<T>(string xml, bool saveToFile)
        {
            try
            {
                //Deserializando o XML
                XmlSerializer xs = new XmlSerializer(typeof(T));
                MemoryStream memoryStream = new MemoryStream(StringToUTF8ByteArray(xml));

                XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, null);

                if (saveToFile)
                {
                    SaveMemoryStream2XML(memoryStream);
                }

                return (T)xs.Deserialize(memoryStream);
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                    throw ex.InnerException;
                else
                    throw ex;
            }
        }
    }
}
